cmake_minimum_required(VERSION 3.10)
project(Sentry-OHOS LANGUAGES C CXX)

set(SENTRY_NATIVE_SRC ${CMAKE_SOURCE_DIR}/../../../../../)
if (NOT THIRDPARTY_DIR)
	set(THIRDPARTY_DIR "${SENTRY_NATIVE_SRC}/external/third_party")
endif()
# Add sentry-ohos shared library
aux_source_directory(ohos_utils OHOS_UTILS_SRC)
add_library(sentry_native_napi SHARED ./sentry.cpp ${OHOS_UTILS_SRC})

# make sure that we build it as a shared lib instead of a static lib
set(BUILD_SHARED_LIBS ON)
set(SENTRY_BUILD_SHARED_LIBS ON)

# Adding sentry-native project
add_subdirectory(${SENTRY_NATIVE_SRC} sentry_build)

# Link to sentry-native
target_link_libraries(sentry_native_napi PRIVATE $<BUILD_INTERFACE:sentry::sentry> ace_napi.z hilog_ndk.z)

# Support 16KB page sizes
target_link_options(sentry_native_napi PRIVATE "-Wl,-z,max-page-size=16384")

function(link_import_library target_name comp lib_name soname)
    set(comp_path "${THIRDPARTY_DIR}/${comp}/${OHOS_ARCH}")
    if(NOT EXISTS "${comp_path}")
        message(FATAL_ERROR "Library not found: ${comp_path} [Component:${comp}]")
    endif()
    if(lib_name MATCHES "\\.a$")
        add_library(${comp} STATIC IMPORTED GLOBAL)
    else()
        add_library(${comp} SHARED IMPORTED GLOBAL)
    endif()

    target_link_directories(${comp} INTERFACE
        "${comp_path}/lib"
    )
    target_include_directories(${comp} INTERFACE
        "${comp_path}/include"
    )
    if (NOT soname)
    set_target_properties(${comp} PROPERTIES
       IMPORTED_LOCATION "${comp_path}/lib/${lib_name}"
    )
    else()
    set_target_properties(${comp} PROPERTIES
       IMPORTED_LOCATION "${comp_path}/lib/${lib_name}"
       IMPORTED_NO_SONAME ON
    )
    file(COPY "${comp_path}/lib/${lib_name}"
         DESTINATION "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}"
    )
    endif()
    target_link_libraries(${target_name} PUBLIC ${comp})
endfunction()

set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
set(CMAKE_SKIP_BUILD_RPATH FALSE)
set(CMAKE_INSTALL_RPATH "$ORIGIN")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)

link_import_library(sentry_native_napi curl libcurl.so.4 FALSE)
link_import_library(sentry_native_napi zstd_1_5_6 libzstd.so.1 FALSE)
link_import_library(sentry_native_napi zlib_1_3_1 libz.so.1 FALSE)
link_import_library(sentry_native_napi nghttp2 libnghttp2.so.14 FALSE)
